package repository

import (
	"gitee.com/yaodae/server-lib-go/common"
	"gitee.com/yaodae/server-lib-go/component/redis"
	"gitee.com/yaodae/server-lib-go/repository/dao"
	"gitee.com/yaodae/server-lib-go/repository/dao/query"
	"gitee.com/yaodae/server-lib-go/utils"
	"strings"
)

type DbRepository interface {
	ParseVal(str string) interface{}
}

type DbRepositorySupport struct {
	Dao dao.DbDao
}

func (db DbRepositorySupport) FindToCache(cacheKey string, convertFunc func(str string) interface{}) interface{} {
	var str = redis.RGet(cacheKey)
	if !utils.IsEmpty(str) {
		return convertFunc(str)
	} else {
		return nil
	}
}

func (db DbRepositorySupport) SaveToCache(key, value string) {
	redis.RSetEX(key, value, common.Day30Second)
}

func (db DbRepositorySupport) FindOne(queryParam query.SelectParam) interface{} {
	return db.Dao.SelectOne(queryParam.Query)
}

func (db DbRepositorySupport) FindList(queryParam query.SelectParam) interface{} {
	var list = make([]interface{}, 0)
	destList := db.Dao.SelectList(queryParam.Query, queryParam.Skip, queryParam.Limit, strings.Split(queryParam.Sort, ",")...)
	if destList != nil {
		list = utils.AnythingToSlice(destList)
	}
	return list
}

func (db DbRepositorySupport) FindCount(queryParam query.SelectParam) uint64 {
	return db.Dao.CountList(queryParam.Query)
}

func (db DbRepositorySupport) Add(dest interface{}) bool {
	num := db.Dao.InsertOne(dest)
	return num > 0
}

func (db DbRepositorySupport) Modify(dest interface{}) bool {
	num := db.Dao.UpdateOne(dest)
	return num > 0
}
